package com.sh.shanhuo.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.sh.shanhuo.R;
import com.sh.shanhuo.utils.Tools;

public class LoadingDialog {

    private Context mContext;
    private String loadingTxt;
    private Dialog dialog;
    private static LoadingDialog instance;
    private TextView loading_msg;

    public static LoadingDialog with(Context context) {
        if (instance == null) {
            synchronized (LoadingDialog.class) {
                if (instance == null) {
                    instance = new LoadingDialog(context);
                }
            }
        }
        return instance;
    }

    private LoadingDialog(Context context) {
        this.mContext = context;
    }


    public LoadingDialog setLoadingTxt(String loadingTxt) {
        this.loadingTxt = loadingTxt;
        return this;
    }
    public LoadingDialog updateLoadingTxt(String loadingTxt) {
        this.loadingTxt = loadingTxt;
        if (loading_msg!=null && !TextUtils.isEmpty(loadingTxt)) {
            loading_msg.setText(loadingTxt);
        }
        return this;
    }

    public void show(Activity activity) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog.cancel();
        }
        dialog = new Dialog(activity, R.style.BaseDialogFullStyle);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.dialog_loading, null);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        loading_msg = dialogView.findViewById(R.id.loading_msg);

        if (TextUtils.isEmpty(loadingTxt)) {
            loading_msg.setText("请稍候...");
        } else {
            loading_msg.setText(loadingTxt);
        }
        if (!activity.isFinishing()) {
            dialog.show();
        }
    }
    public boolean isShowing() {
        return dialog != null && dialog.isShowing();
    }
    public void dismiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog.cancel();
        }
        dialog = null;
        instance = null;
    }

}
